var express = require('express');
var router = express.Router();
var User = require('../models/users');
var Group = require('../models/group');
var util = require('../util/util.js');
var Answer = require('../models/answer');
var ObjectID = require('mongodb').ObjectID;
const multer = require('multer');
var path = require('path');
const dir = path.resolve(__dirname, '../tmp');
// // 图片大小限制KB
const SIZELIMIT = 500000;
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, dir);  //这里是图片存储路劲
  },
  filename: function (req, file, cb) {
    console.log(req.body)
    cb(null, Date.now() + '-' + file.originalname);

  }
});
var upload = multer({
  storage: storage
});
// 上传队伍图片https://www.jb51.net/article/180636.htm
router.use('/addGroupImg', upload.single('file'), function (req, res, next) {
  let { groupId } = req.body;
  // 即将上传图片的key值 form-data对象{key: value}
  // 检查是否有文件待上传
  if (req.file === undefined) {
    return res.send({
      status: '1',
      errno: -1,
      msg: 'no file'
    });
  }
  const { size, mimetype, filename } = req.file;
  const types = ['jpg', 'jpeg', 'png', 'gif'];
  const tmpTypes = mimetype.split('/')[1];
  // 检查文件大小
  // if (size >= SIZELIMIT) {
  //   return res.send({
  //     status: '1',
  //     errno: -1,
  //     msg: 'file is too large'
  //   });
  // }
  // 检查文件类型
  if (types.indexOf(tmpTypes) < 0) {
    return res.send({
      status: '1',
      errno: -1,
      msg: 'not accepted filetype'
    });
  }
  // 路径可根据设置的静态目录指定
  // const url = '/public/img/' + filename;
  const url = filename;
  Group.findOne({ _id: groupId }).then(groupInfo => {
    groupInfo.groupImg = url;
    groupInfo.save().then(newGroupInfo => {
      res.json({
        status: '0',
        errno: 0,
        msg: 'upload success',
        data: url
      });
    })
  })

  // var url = 'http://' + req.headers.host + '/tmp/' + req.file.originalname;
  // console.log('url', url)
  // res.json({
  //   status: '0',
  //   data: url
  // })
});
// 查系统中所有的队伍（除用户所在队伍）
router.post('/allGroupList', function (req, res, next) {
  let token = req.body.token;
  let gropsArr = [];
  let arr = [];
  User.findOne({
    token: token
  }).then((userInfo) => {
    gropsArr = userInfo.gropsArr;
    if (gropsArr.length > 0) {
      // 当用户下有自己的队伍时
      gropsArr.forEach((item) => {
        arr.push({ '_id': { $ne: item } })
      })
      arr.push({ 'unjoinNum': { $ne: 0 } })
      Group.find({
        $and: arr
      }, { "userIdArr": 0, "answerIdArr": 0 }).then((groupInfo) => {
        // 从系统队伍中屏蔽掉自己的队伍
        if (groupInfo) {
          res.json({
            status: '0',
            data: groupInfo
          })
        } else {
          res.json({
            status: '0',
            msg: '还没有可加入的队伍'
          })
        }
      }).catch((err) => {
        res.json({
          status: '1',
          msg: err
        })
      })
    } else {
      // 当用户下没有自己的队伍时
      Group.find({}, { "userIdArr": 0, "answerIdArr": 0 }).then((groupInfo) => {
        res.json({
          status: '0',
          data: groupInfo
        })
      })
    }
  }).catch((err) => {
    res.json({
      status: '1',
      msg: err
    })
  })

})
// 查用户下加入的队伍列表
router.post('/userGroupList', function (req, res, next) {
  var token = req.body.token;
  var arr = [];
  User.findOne({
    token: token
  }).then((userInfo) => {
    if (userInfo) {
      let gropsArr = userInfo.gropsArr;
      let len = gropsArr.length;
      if (len > 0) {
        gropsArr.forEach((item) => {
          arr.push({ '_id': new ObjectID(item) })
        })
        Group.find(
          { $or: arr },
          { "answerIdArr": 0 }).then(myGroupInfo => {
            res.json({
              status: '0',
              data: myGroupInfo ? myGroupInfo : ''
            })
          }).catch(err => {
            res.json({
              status: '1',
              msg: err
            })
          })
      } else {
        res.json({
          status: '0',
          data: []
        })
      }
    } else {
      res.json({
        status: '1',
        msg: '需要重新登录'
      })
    }
  }).catch((err) => {
    res.json({
      status: '1',
      msg: '程序出错'
    })
  })
})
// 新建队伍
router.post('/addGroup', function (req, res, next) {
  let { token, groupName, maxNum, groupDescribe } = req.body;
  let userId = ''
  User.findOne({
    token: token
  }).then((userInfo) => {
    userId = userInfo._id
    var groupInfo = {
      groupName,
      maxNum,
      userId,
      groupDescribe,
      unjoinNum: maxNum - 1
    }
    addGroup(groupInfo).then((newGroupInfo) => {
      if (newGroupInfo) {
        res.json({
          status: '0',
          msg: '创建队伍成功',
          data: newGroupInfo
        })
      } else {
        res.json({
          status: '0',
          msg: '创建失败，请稍后再试'
        })
      }
      userInfo.gropsArr.push(newGroupInfo._id)
      userInfo.save()
    }).catch((err) => {
      res.json({
        status: '1',
        msg: err
      })
    })

  })
})
// 创建新队伍
function addGroup (data) {
  return new Promise((resolve, reject) => {
    var groupDate = util.nowYMD();
    var groupTime = util.nowHM();
    var userIdArr = [];
    userIdArr.push(data.userId);
    var group = new Group({
      answerIdArr: [],
      groupDate: groupDate,
      groupTime: groupTime,
      groupImg: '',
      groupName: data.groupName,
      groupDescribe: data.groupDescribe,
      maxNum: data.maxNum,
      mainUser: data.userId,
      userIdArr: userIdArr,
      unjoinNum: data.unjoinNum
    })
    group.save().then((newGroupInfo) => {
      resolve(newGroupInfo)

    }).catch((err) => {
      reject(err)

    })
  })

}
// 加入队伍
router.post('/joinGroup', function (req, res, next) {
  let { token, groupId } = req.body;

  User.findOne({ token: token }).then(userInfo => {
    // 在用户下存进队伍名称
    console.log(groupId)
    Group.findOne({ _id: groupId }).then(groupInfo => {
      console.log('111', groupInfo)
      // 该队伍下加入用户id
      groupInfo.userIdArr.push(userInfo._id);
      // 队伍人数增加
      groupInfo.unjoinNum--;
      groupInfo.save();
      userInfo.gropsArr.push(groupInfo._id);
      userInfo.save();
      console.log(userInfo._id, groupInfo._id)
      res.json({
        status: '0',
        msg: '加入队伍成功'
      })
    }).catch(err => {
      res.json({
        status: '1',
        msg: '加入失败请稍后再试' + err
      })
    })

  }).catch(err => {
    res.json({
      status: '1',
      msg: err
    })
  })
})
// 获取队伍信息
router.post('/getGroupDetail', function (req, res, next) {
  let { groupId } = req.body;
  Group.findOne({ _id: groupId }, { "userIdArr": 0, "answerIdArr": 0 }).then(groupInfo => {
    res.json({
      status: '0',
      data: groupInfo
    })
  }).catch(err => {
    res.json({
      status: '1',
      msg: err
    })
  })
})
// 获取队伍用户
router.post('/getGroupUsers', function (req, res, next) {
  let { groupId } = req.body;
  let arr = [];
  Group.findOne({ _id: groupId }).then(groupInfo => {
    groupInfo.userIdArr.forEach(item => {
      arr.push({ '_id': new ObjectID(item) })
    })
    User.find({ $or: arr }, { "nickName": 1, "avatarUrl": 1, "_id": 1 }).then(userList => {
      res.json({
        status: '0',
        data: userList
      })
    }).catch(err => {
      res.json({
        status: '1',
        msg: err
      })
    })
  }).catch(err => {
    res.json({
      status: '1',
      msg: err
    })
  })
})
// 获取队伍问题信息
router.get('/getGroupAQList', function (req, res, next) {
  let { groupId } = req.query;
  let arr = [];
  Group.findOne({ _id: groupId }).then(groupInfo => {
    groupInfo.answerIdArr.forEach(item => {
      arr.push({ '_id': new ObjectID(item) })
    })
    Answer.find({ $or: arr }, { "visiteUsers": 0 }).then(aqList => {
      res.json({
        status: '0',
        data: aqList
      })
    }).catch(err => {
      res.json({
        status: '1',
        msg: err
      })
    })
  }).catch(err => {
    res.json({
      status: '1',
      msg: err
    })
  })
});
// 队伍里只显示我发布的问题
router.post('/getMyAQList', function (req, res, next) {
  let { groupId, token } = req.body;
  User.findOne({ token: token }).then(userInfo => {
    let userId = userInfo._id;
    Answer.find({ $and: [{ 'userId': userId }, { 'groupId': groupId }] }).then(aqList => {
      res.json({
        status: '0',
        data: aqList
      })
    }).catch(err => {
      res.json({
        status: '1',
        msg: err
      })
    });
  })

});
// 修改队伍信息
router.post('/updateGtoup', function (req, res, next) {
  let { groupId, groupName, groupDes } = req.body;
  Group.findOne({ _id: groupId }).then(groupInfo => {
    groupInfo.groupName = groupName;
    groupInfo.groupDescribe = groupDes;
    groupInfo.save().then(() => {
      res.json({
        status: '0',
        msg: '更新成功'
      })
    }).catch(err => {
      res.json({
        status: '1',
        msg: err
      })
    })
  }).catch(err => {
    res.json({
      status: '1',
      msg: err
    })
  })
})
// 退出队伍
router.post('/exitGroup', function (req, res, next) {
  let { groupId, token } = req.body;
  User.findOne({ token: token }).then(userInfo => {
    let userId = userInfo._id.toString();
    userInfo.gropsArr.forEach((item, index) => {
      if (groupId == item) {
        userInfo.gropsArr.splice(index, 1)
        userInfo.save();
      }
    });
    Group.findOne({ _id: groupId }).then(groupInfo => {
      groupInfo.unjoinNum++;
      groupInfo.userIdArr.forEach((item, index1) => {
        if (item == userId) {
          groupInfo.mainUser = groupInfo.userIdArr[index1 + 1];
          groupInfo.userIdArr.splice(index1, 1);
          groupInfo.save().then((newgroupInfo) => {
            res.json({
              status: '0',
              data: newgroupInfo,
              msg: '退出成功'
            })
          });
        }
      })
    }).catch(err => {
      res.json({
        status: '1',
        msg: err
      })
    })
  }).catch(err => {
    res.json({
      status: '1',
      msg: err
    })
  })

})
// 解散队伍
router.post('/deleteGroup', function (req, res, next) {
  let { groupId, token } = req.body;
  User.findOne({ token: token }).then(userInfo => {
    userInfo.gropsArr.forEach((item, index) => {
      if (groupId == item) {
        userInfo.gropsArr.splice(index, 1)
        userInfo.save();
      }
    });
    Group.deleteOne({ _id: groupId }).then(() => {
      res.json({
        status: '0',
        msg: "删除成功"
      })
    }).catch(err => {
      res.json({
        status: '1',
        msg: err
      })
    })
  }).catch(err => {
    res.json({
      status: '1',
      msg: err
    })
  })

})
module.exports = router;
